<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图书管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            padding-top: 20px;
            background-color: #f5f5f5;
        }
        .container {
            max-width: 1200px;
        }
        .book-card {
            margin-bottom: 20px;
            transition: transform 0.3s;
        }
        .book-card:hover {
            transform: translateY(-5px);
        }
        .form-container {
            background-color: #fff;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            margin-bottom: 30px;
        }
        .book-list {
            margin-top: 30px;
        }
        .badge {
            font-size: 0.8rem;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1 class="text-center mb-4">图书管理系统</h1>
        <p class="text-center text-muted mb-5">使用 ASP.NET Core 和 Entity Framework Core 构建的图书管理系统</p>

        <div class="form-container">
            <h3 class="mb-3">添加/编辑图书</h3>
            <form id="bookForm">
                <input type="hidden" id="bookId" value="0">
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label for="title" class="form-label">书名</label>
                        <input type="text" class="form-control" id="title" required>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label for="author" class="form-label">作者</label>
                        <input type="text" class="form-control" id="author" required>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-4 mb-3">
                        <label for="publishYear" class="form-label">出版年份</label>
                        <input type="number" class="form-control" id="publishYear" required>
                    </div>
                    <div class="col-md-4 mb-3">
                        <label for="isbn" class="form-label">ISBN</label>
                        <input type="text" class="form-control" id="isbn">
                    </div>
                    <div class="col-md-4 mb-3">
                        <label for="price" class="form-label">价格</label>
                        <input type="number" class="form-control" id="price" step="0.01" required>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label for="category" class="form-label">分类</label>
                        <input type="text" class="form-control" id="category">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label for="isAvailable" class="form-label">是否可借阅</label>
                        <select class="form-select" id="isAvailable">
                            <option value="true">是</option>
                            <option value="false">否</option>
                        </select>
                    </div>
                </div>
                <div class="mb-3">
                    <label for="description" class="form-label">描述</label>
                    <textarea class="form-control" id="description" rows="3"></textarea>
                </div>
                <div class="d-flex justify-content-between">
                    <button type="submit" class="btn btn-primary">保存</button>
                    <button type="button" class="btn btn-secondary" id="resetBtn">重置</button>
                </div>
            </form>
        </div>

        <div class="row mb-4">
            <div class="col-md-6">
                <div class="input-group">
                    <input type="text" class="form-control" id="searchInput" placeholder="搜索图书...">
                    <button class="btn btn-outline-secondary" type="button" id="searchBtn">搜索</button>
                </div>
            </div>
            <div class="col-md-6">
                <div class="d-flex justify-content-end">
                    <div class="btn-group" role="group">
                        <button type="button" class="btn btn-outline-primary" id="filterAll">全部</button>
                        <button type="button" class="btn btn-outline-primary" id="filterAvailable">可借阅</button>
                        <button type="button" class="btn btn-outline-primary" id="filterUnavailable">不可借阅</button>
                    </div>
                </div>
            </div>
        </div>

        <div class="alert alert-info" role="alert" id="messageBox" style="display: none;"></div>

        <div class="row book-list" id="bookList">
            <!-- 图书列表将通过JavaScript动态生成 -->
            <div class="text-center">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">加载中...</span>
                </div>
                <p class="mt-2">正在加载图书数据...</p>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // API基础URL
            const apiUrl = '/api/books';
            let books = [];
            
            // 获取所有图书
            function fetchBooks() {
                fetch(apiUrl)
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('获取图书数据失败');
                        }
                        return response.json();
                    })
                    .then(data => {
                        books = data;
                        renderBooks(books);
                    })
                    .catch(error => {
                        showMessage(error.message, 'danger');
                    });
            }
            
            // 渲染图书列表
            function renderBooks(booksToRender) {
                const bookList = document.getElementById('bookList');
                bookList.innerHTML = '';
                
                if (booksToRender.length === 0) {
                    bookList.innerHTML = '<div class="col-12 text-center"><p>没有找到图书</p></div>';
                    return;
                }
                
                booksToRender.forEach(book => {
                    const availabilityBadge = book.isAvailable 
                        ? '<span class="badge bg-success">可借阅</span>' 
                        : '<span class="badge bg-danger">不可借阅</span>';
                    
                    const bookCard = document.createElement('div');
                    bookCard.className = 'col-md-4';
                    bookCard.innerHTML = `
                        <div class="card book-card">
                            <div class="card-body">
                                <h5 class="card-title">${book.title}</h5>
                                <h6 class="card-subtitle mb-2 text-muted">${book.author} (${book.publishYear})</h6>
                                <p class="card-text">${book.description || '暂无描述'}</p>
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <span class="badge bg-info">${book.category || '未分类'}</span>
                                        ${availabilityBadge}
                                    </div>
                                    <div>
                                        <span class="text-primary fw-bold">¥${book.price.toFixed(2)}</span>
                                    </div>
                                </div>
                                <div class="mt-3">
                                    <button class="btn btn-sm btn-outline-primary edit-btn" data-id="${book.id}">编辑</button>
                                    <button class="btn btn-sm btn-outline-danger delete-btn" data-id="${book.id}">删除</button>
                                </div>
                            </div>
                        </div>
                    `;
                    bookList.appendChild(bookCard);
                });
                
                // 添加编辑按钮事件监听
                document.querySelectorAll('.edit-btn').forEach(button => {
                    button.addEventListener('click', function() {
                        const bookId = this.getAttribute('data-id');
                        editBook(bookId);
                    });
                });
                
                // 添加删除按钮事件监听
                document.querySelectorAll('.delete-btn').forEach(button => {
                    button.addEventListener('click', function() {
                        const bookId = this.getAttribute('data-id');
                        if (confirm('确定要删除这本书吗？')) {
                            deleteBook(bookId);
                        }
                    });
                });
            }
            
            // 编辑图书
            function editBook(id) {
                const book = books.find(b => b.id == id);
                if (book) {
                    document.getElementById('bookId').value = book.id;
                    document.getElementById('title').value = book.title;
                    document.getElementById('author').value = book.author;
                    document.getElementById('publishYear').value = book.publishYear;
                    document.getElementById('isbn').value = book.isbn || '';
                    document.getElementById('price').value = book.price;
                    document.getElementById('category').value = book.category || '';
                    document.getElementById('isAvailable').value = book.isAvailable.toString();
                    document.getElementById('description').value = book.description || '';
                    
                    window.scrollTo({ top: 0, behavior: 'smooth' });
                }
            }
            
            // 删除图书
            function deleteBook(id) {
                fetch(`${apiUrl}/${id}`, {
                    method: 'DELETE'
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('删除图书失败');
                    }
                    showMessage('图书删除成功', 'success');
                    fetchBooks();
                })
                .catch(error => {
                    showMessage(error.message, 'danger');
                });
            }
            
            // 保存图书（添加或更新）
            document.getElementById('bookForm').addEventListener('submit', function(e) {
                e.preventDefault();
                
                const bookId = document.getElementById('bookId').value;
                const book = {
                    id: parseInt(bookId) || 0,
                    title: document.getElementById('title').value,
                    author: document.getElementById('author').value,
                    publishYear: parseInt(document.getElementById('publishYear').value),
                    isbn: document.getElementById('isbn').value,
                    price: parseFloat(document.getElementById('price').value),
                    category: document.getElementById('category').value,
                    isAvailable: document.getElementById('isAvailable').value === 'true',
                    description: document.getElementById('description').value
                };
                
                const method = bookId == 0 ? 'POST' : 'PUT';
                const url = bookId == 0 ? apiUrl : `${apiUrl}/${bookId}`;
                
                fetch(url, {
                    method: method,
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(book)
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('保存图书失败');
                    }
                    showMessage('图书保存成功', 'success');
                    resetForm();
                    fetchBooks();
                })
                .catch(error => {
                    showMessage(error.message, 'danger');
                });
            });
            
            // 重置表单
            document.getElementById('resetBtn').addEventListener('click', resetForm);
            
            function resetForm() {
                document.getElementById('bookId').value = '0';
                document.getElementById('bookForm').reset();
            }
            
            // 搜索功能
            document.getElementById('searchBtn').addEventListener('click', function() {
                const searchTerm = document.getElementById('searchInput').value.toLowerCase();
                if (searchTerm) {
                    const filteredBooks = books.filter(book => 
                        book.title.toLowerCase().includes(searchTerm) || 
                        book.author.toLowerCase().includes(searchTerm) ||
                        (book.category && book.category.toLowerCase().includes(searchTerm))
                    );
                    renderBooks(filteredBooks);
                } else {
                    renderBooks(books);
                }
            });
            
            // 过滤功能
            document.getElementById('filterAll').addEventListener('click', function() {
                renderBooks(books);
            });
            
            document.getElementById('filterAvailable').addEventListener('click', function() {
                const availableBooks = books.filter(book => book.isAvailable);
                renderBooks(availableBooks);
            });
            
            document.getElementById('filterUnavailable').addEventListener('click', function() {
                const unavailableBooks = books.filter(book => !book.isAvailable);
                renderBooks(unavailableBooks);
            });
            
            // 显示消息
            function showMessage(message, type) {
                const messageBox = document.getElementById('messageBox');
                messageBox.textContent = message;
                messageBox.className = `alert alert-${type}`;
                messageBox.style.display = 'block';
                
                setTimeout(() => {
                    messageBox.style.display = 'none';
                }, 3000);
            }
            
            // 初始加载图书
            fetchBooks();
        });
    </script>
</body>
</html>